package com.zhengke.controller.coolxin;

import com.alibaba.fastjson.JSONArray;
import com.zhengke.common.util.object.AjaxDone;
import com.zhengke.common.util.tools.CommonUtil;
import com.zhengke.common.util.tools.DateUtil;
import com.zhengke.common.util.tools.FdfsUtils;
import com.zhengke.common.util.tools.LoadProperties;
import com.zhengke.pojo.TvUserOpera;
import com.zhengke.pojo.archie.CurrentUser;
import com.zhengke.pojo.archie.OrderPagination;
import com.zhengke.pojo.coolxin.MallGoodsClass;
import com.zhengke.pojo.coolxin.TypeMsg;
import com.zhengke.service.ExperieService;
import com.zhengke.service.IDiscountService;
import com.zhengke.service.coolxin.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * *******************************
 * 项目名称：tvmall-parent
 * 文件名称：TypeController
 * 类说明：  分类商品
 * 创建时间：2020/2/4 13:01
 *
 * @author 王鑫
 * @version 1.0
 * *******************************
 */
@Controller
public class TypeController extends OrderPagination {

    @Autowired
    private TypeService service;
    @Autowired
    private IDiscountService discountService;

    @Autowired
    private ExperieService experieService;
    private AjaxDone json;

    /**
     * 到分类列表页
     *
     * @return
     */
    @RequestMapping("toTypeList.do")
    public String toTypeList(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
        CurrentUser user = getCurrentUser(request, response);
        TvUserOpera tvUserOpera = new TvUserOpera();
        tvUserOpera.setId(CommonUtil.createUUID());
        tvUserOpera.setUserId(Integer.parseInt(user.getTvnNo()));
        tvUserOpera.setUserName(user.getUserName());
        tvUserOpera.setType(1);
        tvUserOpera.setTime(DateUtil.currentTime());
        tvUserOpera.setText("分类商品");
        discountService.insertSelective(tvUserOpera);
        model.put("tmp", new Date());
        return "tv/type/typeList";
    }

    /**
     * 分类列表
     */
    @RequestMapping("typeData.do")
    public void typeData(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<MallGoodsClass> list = service.queryTypeList();
            List<Map<String, String>> rtnList = new ArrayList<Map<String, String>>();
            String notFoundPic = LoadProperties.findValue("losePicForList");
            String fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
            for (MallGoodsClass mg : list) {
                Map<String, String> temp = new HashMap<String, String>();
                String picPath = mg.getGcPicpath();
                if (picPath == null || "".equals(picPath))
                    picPath = "view.do?path=" + request.getSession().getServletContext().getRealPath(notFoundPic);
                else {
                    picPath = fileServerUrl + picPath;
                    Boolean exist = FdfsUtils.isExist(picPath);
                    if (!exist) {
                        picPath = "view.do?path=" + request.getSession().getServletContext().getRealPath(notFoundPic);
                    }
                }
                temp.put("picPath", picPath);
                temp.put("typeName", mg.getGcName());
                temp.put("typeId", mg.getGcId().toString());
                rtnList.add(temp);
            }
            response.setCharacterEncoding("utf-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().print("var dataList=" + JSONArray.toJSON(rtnList));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 到分类商品列表页面
     *
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("toTypeGoodList.do")
    public String toTypeGoodList(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
        String typeId = request.getParameter("typeId");
        CurrentUser user = getCurrentUser(request, response);
        MallGoodsClass mallGoodsClass = service.queryById(Integer.parseInt(typeId));
        if (mallGoodsClass != null) {
            TvUserOpera tvUserOpera = new TvUserOpera();
            tvUserOpera.setId(CommonUtil.createUUID());
            tvUserOpera.setUserId(Integer.parseInt(user.getTvnNo()));
            tvUserOpera.setUserName(user.getUserName());
            tvUserOpera.setType(3);
            tvUserOpera.setTime(DateUtil.currentTime());
            tvUserOpera.setText(mallGoodsClass.getGcName());

            discountService.insertSelective(tvUserOpera);
        }
        model.put("tmp", new Date());
        model.put("typeId", typeId);
        return "tv/type/typeGoodList";
    }

    /**
     * 分类商品列表
     */
    @RequestMapping("typeGoodData.do")
    public void typeGoodData(HttpServletRequest request, HttpServletResponse response) {
        CurrentUser user = getCurrentUser(request, response);
        String pointId = user.getStationId();//服务点ID
        String typeId = request.getParameter("typeId");
        try {
            List<TypeMsg> list = service.queryTypeGoodList(typeId, pointId);

            List<Map<String, String>> rtnList = new ArrayList<Map<String, String>>();
            String notFoundPic = LoadProperties.findValue("losePicForList");
            for (TypeMsg obj : list) {
                Map<String, String> temp = new HashMap<String, String>();
                String picPath = obj.getThumbPicPath() == null ? "" : obj.getThumbPicPath();
                if (picPath == null || "".equals(picPath))
                    picPath = "view.do?path=" + request.getSession().getServletContext().getRealPath(notFoundPic);
                else {
                    //判断如果不为空的话
                    picPath = LoadProperties.findValue("FILE_SERVER_URL") + picPath;
                    Boolean exist = FdfsUtils.isExist(picPath);
                    if (!exist) {
                        picPath = "view.do?path=" + request.getSession().getServletContext().getRealPath(notFoundPic);
                    }
                }
                temp.put("commonGoodsId", obj.getGoodsCommonId() == null ? "" : obj.getGoodsCommonId());
                temp.put("picPath", picPath);
                temp.put("goodsId", obj.getGoodsId() == null ? "" : obj.getGoodsId());
                temp.put("goodsName", obj.getGoodsName() == null ? "" : obj.getGoodsName());
                temp.put("goodsPromotionPrice", obj.getCommonPrice() == null ? "" : "￥" + obj.getCommonPrice());
                temp.put("type", obj.getType());
                rtnList.add(temp);
            }
            response.setCharacterEncoding("utf-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().print("var dataList=" + JSONArray.toJSON(rtnList));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 到商品详情页面
     *
     * @return
     */
    @RequestMapping("toTypeGoodsDetail.do")
    public String toGoodsDetail(int goodsId, String orderNumber, String type, String pageTitle, ModelMap model, HttpServletRequest request) {
        model.put("tmp", new Date());
        try {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

            list = experieService.queryExperie(goodsId);
            String fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
            String notInfoPic = LoadProperties.findValue("loseInfoPicForGoodsDetail");
            for (Map<String, Object> obj : list) {
                String infoPicPath = obj.get("info_picPath").toString();
                String commonGoodsId = obj.get("common_goods_id").toString();
                if (infoPicPath == null || "".equals(infoPicPath))
                    infoPicPath = "view.do?path=" + request.getSession().getServletContext().getRealPath(notInfoPic);
                else {
                    infoPicPath = fileServerUrl + infoPicPath;
                    Boolean exist = FdfsUtils.isExist(infoPicPath);
                    if (!exist) {
                        infoPicPath = "view.do?path=" + request.getSession().getServletContext().getRealPath(notInfoPic);
                    }
                }

                List<String> rtnList = new ArrayList<String>();

                if (obj.get("picPath1") != null && !"".equals(obj.get("picPath1")))
                    rtnList.add(fileServerUrl + obj.get("picPath1").toString());
                if (obj.get("picPath2") != null && !"".equals(obj.get("picPath2")))
                    rtnList.add(fileServerUrl + obj.get("picPath2").toString());
                if (obj.get("picPath3") != null && !"".equals(obj.get("picPath3")))
                    rtnList.add(fileServerUrl + obj.get("picPath3").toString());
                if (obj.get("picPath4") != null && !"".equals(obj.get("picPath4")))
                    rtnList.add(fileServerUrl + obj.get("picPath4").toString());
                if (obj.get("picPath5") != null && !"".equals(obj.get("picPath5")))
                    rtnList.add(fileServerUrl + obj.get("picPath5").toString());

                if (rtnList.size() == 0) {
                    String notFoundPic = LoadProperties.findValue("losePicForGoods");
                    rtnList.add("view.do?path=" + request.getSession().getServletContext().getRealPath(notFoundPic));
                }


                String shippingFee = obj.get("shipping_fee") == null ? "" : obj.get("shipping_fee").toString();
                double s = Double.parseDouble(shippingFee) * (2);
                model.put("shippingFee", s);//运费

                model.put("goodsId", commonGoodsId);
                model.put("picList", rtnList);
                model.put("picList", rtnList);
                model.put("goodsName", obj.get("goods_name"));
                model.put("goodsPrice", "￥" + obj.get("goods_price"));//打折价
                model.put("deliveryWay", "门店自提");//收货方式
                model.put("supplierName", obj.get("supplier_name"));//供应商名称
                model.put("supplierId", obj.get("supplier_id"));//供应商id
                model.put("infoPicPath", infoPicPath);//介绍图片
                model.put("awardedIntegral", obj.get("awarded_integral"));//赠送积分
                model.put("specifications", obj.get("specifications"));//商品规格
            }
            if (orderNumber == null || "".equals(orderNumber))
                model.put("orderNumber", 1);
            else
                model.put("orderNumber", orderNumber);

            //图片查询滚动时间
            model.put("time", "1000");//轮播图片滚动时间
            if ("0".equals(type) || "2".equals(type)) {
                model.put("show", "0");//显示类型
            } else {
                model.put("show", "1");//显示类型
            }
            model.put("type", type);//商品类型


        } catch (Exception e) {
            e.printStackTrace();
        }
        return "tv/type/goodsDetail";
    }

    public AjaxDone getJson() {
        return json;
    }

    public void setJson(AjaxDone json) {
        this.json = json;
    }
}
